import { Badge, Select, Spin, Tabs, Tooltip, Typography } from 'antd';
import React, { useEffect, useState, useMemo } from 'react';
import cls from './index.module.less';
import orgCtrl from '@/ts/controller';
import EntityIcon from '@/components/Common/GlobalComps/entityIcon';
import OrgIcons from '@/components/Common/GlobalComps/orgIcons';
import SessionBody from '@/components/DataPreview/session/content';
import FormView from '@/executor/open/view/form/formView';
import AssetModule from '@/components/DataPreview/session/WorkBench/AssetModule';
import { MallTemplate } from '@/executor/open/mallTemplate/pages';
import { DashboardTemplateHomeView } from '@/executor/open/dashboardTemplate';
import { IMallTemplate } from '@/ts/core/thing/standard/page/mallTemplate';
import { TotalView } from '@/ts/core/thing/standard/view/totalView';
import LedgerForm from '@/executor/open/view/ledger/LedgerForm';
import { ICompany, IView } from '@/ts/core';
import { command, kernel } from '@/ts/base';
import HomeChat from './components/HomeChat';
import RelationDirectory from './components/RelationDirectory';

const defaultActions = [
  { text: '首页', icon: 'homebar/home', count: 0, bodyType: 'home' },
  { text: '工作台', icon: 'homebar/bench', count: 0, bodyType: 'bench' },
  { text: '消息', icon: 'homebar/chat', count: 0, bodyType: 'chat' },
  { text: '动态', icon: 'homebar/activity', count: 0, bodyType: 'activity' },
  { text: '文件', icon: 'homebar/store', count: 0, bodyType: 'file' },
  { text: '待办', icon: 'homebar/work', count: 0, bodyType: 'work' },
  { text: '数据', icon: 'homebar/store', count: 0, bodyType: 'store' },
  { text: '成员', icon: 'homebar/relation', count: 0, bodyType: 'relation' },
];
const Home: React.FC = () => {
  const [bodyType, setBodyType] = useState<any>('bench');
  const [toolBar, setToolBar] = useState(orgCtrl.toolbarLayout);
  const [loading, setLoading] = useState(false);
  const [workCount, setWorkCount] = useState<number>(0);
  const [orderCount, setOrderCount] = useState<number>(0);
  const [tops, setTops] = useState<any[]>([]);
  const [commonStatus, setCommonStatus] = useState<any[]>([]);
  const fetchDependencies = async () => {
    setLoading(true);
    try {
      const [newTops, newCommonStatus, newWorkCount, newOrderCount] = await Promise.all([
        orgCtrl.home.getTops(),
        orgCtrl.home.current.webSiteProvider.loadConfig(),
        getWorkCount(),
        getOrderCount(),
      ]);
      setTops(newTops);
      setCommonStatus(newCommonStatus);
      setWorkCount(newWorkCount);
      setOrderCount(newOrderCount);
    } finally {
      setLoading(false);
    }
  };
  const actions = useMemo(() => {
    const _actionsMerged = defaultActions.map((v) => {
      const find = commonStatus.find((item: any) => item.bodyType === v.bodyType);
      const updatedCount = v.bodyType === 'work' ? workCount + orderCount : v.count;
      if (find) {
        return { ...v, status: find.status, count: updatedCount };
      }
      return v;
    });

    return [
      ..._actionsMerged,
      { bodyType: 'splitLine' },
      ...tops.map((item) => ({
        text: item.name,
        icon: item.metadata,
        count: 0,
        bodyType: item,
        key: item.id,
      })),
    ];
  }, [commonStatus, workCount, orderCount, tops]);

  /** 获取办事数量 */
  const getWorkCount = async (): Promise<number> => {
    const target = orgCtrl.home.current;
    const todos = await orgCtrl.work.loadTodos(true, target.id);
    return todos.length;
  };

  /** 获取订单数量 */
  const getOrderCount = async (): Promise<number> => {
    const target = orgCtrl.home.current;
    if (target.typeName === '单位') {
      return (target as ICompany).getOrderCount();
    }
    return 0;
  };

  useEffect(() => {
    fetchDependencies();
    const id = command.subscribeByFlag('topChanged', async (flag: number) => {
      if (flag === 1) {
        setLoading(true);
        return;
      } else if (flag === 2) {
        setLoading(false);
      }
      await fetchDependencies();
    });

    const tid = command.subscribeByFlag('toolbarLayoutChanged', () => {
      setToolBar(orgCtrl.toolbarLayout);
    });

    kernel.subscribe(`mall-change`, ['mall-change'], (data: any) => {
      if (data?.operate === 'mall-change') {
        fetchDependencies();
      }
    });

    const workId = orgCtrl.work.notity.subscribe(() => fetchDependencies());

    return () => {
      orgCtrl.work.notity.unsubscribe(workId);
      command.unsubscribeByFlag(id);
      command.unsubscribeByFlag(tid);
    };
  }, []);

  const NavItem = (item: any) => {
    if (item.bodyType === 'splitLine') {
      return <div className={cls.splitLine}></div>;
    }
    const selected = item.bodyType === bodyType;
    let content =
      typeof item.icon === 'string' ? (
        <OrgIcons size={20} type={item.icon} notAvatar />
      ) : (
        <EntityIcon disableInfo entity={item.icon} size={22} />
      );
    if (item.count > 0) {
      content = (
        <Badge count={item.count} size="small">
          {content}
        </Badge>
      );
    }
    return (
      <a
        key={item.key ?? item.bodyType}
        onClick={() => {
          setBodyType(item.bodyType);
        }}
        className={`${cls['navbar-item']} ${
          selected ? cls['navbar-item_selected'] : ''
        }`}>
        {content}
        <span className={cls['navbar-item-text']}>
          {item.text.length < 5 ? (
            item.text
          ) : (
            <Tooltip placement="bottomLeft" title={item.text}>
              {item.text}
            </Tooltip>
          )}
        </span>
      </a>
    );
  };
  const renderApp = (entity: any) => {
    const typeName = entity.metadata?.typeName;
    let data = <></>;
    switch (typeName) {
      case '应用':
        data = <AssetModule key={entity.key} selectXApp={entity}></AssetModule>;
        break;
      case '商城模板':
        data = <MallTemplate current={entity as IMallTemplate} />;
        break;
      case '视图':
        if (entity.groupTags.includes('图表视图')) {
          data = <DashboardTemplateHomeView current={entity as any} />;
          break;
        } else if (entity instanceof TotalView) {
          data = (
            <LedgerForm
              isFull={false}
              current={entity as IView}
              form={entity.metadata as any}
              directory={entity.directory}
            />
          );
        } else {
          data = (
            <FormView
              form={entity.metadata}
              directory={entity.directory}
              isMemberView={false}
            />
          );
        }
        break;
    }
    return data;
  };

  const onChange = async (id: string) => {
    const space = orgCtrl.home.spaces.find((i) => i.id === id);
    if (space) {
      await orgCtrl.home.switchSpace(space);
    }
  };
  if (!orgCtrl.data.inited) {
    return (
      <Spin spinning={true} size="large">
        <div style={{ width: '100%', height: '100%' }}></div>
      </Spin>
    );
  }

  return (
    <Spin spinning={loading} size="large" className={cls.loading}>
      <div
        className={cls.homepage}
        style={toolBar === 'top' ? { display: 'inline-flex' } : {}}>
        <div className={toolBar === 'top' ? cls.homeBarLeft : cls.homeBarTop}>
          <Select
            bordered={false}
            value={orgCtrl.home.current.id}
            style={{
              width: '200px',
              height: 40,
              background: 'transparent',
              position: 'absolute',
            }}
            size="large"
            onChange={onChange}
            options={orgCtrl.home.spaces.map((page) => {
              return {
                label: (
                  <Typography.Text
                    style={{ width: '160px' }}
                    ellipsis={{
                      tooltip: {
                        title: <EntityIcon entityId={page.id} size={26} showName />,
                        color: '#fff',
                      },
                    }}>
                    <EntityIcon entityId={page.id} size={26} />
                    &nbsp;
                    {page.name}
                  </Typography.Text>
                ),
                value: page.id,
              };
            })}
          />
          <Tabs
            className={cls.navbar}
            defaultActiveKey="bench"
            tabBarGutter={6}
            tabPosition={toolBar === 'top' ? 'left' : 'top'}
            spellCheck={false}
            items={actions
              .filter((v) => v.status !== 0)
              .map((item) => {
                return {
                  label: NavItem(item),
                  key: item.key || item.bodyType,
                };
              })}
            tabBarExtraContent={
              <div
                style={{
                  display: 'flex',
                  flexDirection: toolBar === 'top' ? 'column' : 'row',
                }}>
                {[
                  {
                    text: '在线',
                    icon: 'homebar/line-chart-up-03',
                    count: 0,
                    visible: orgCtrl.home.isUser,
                    bodyType: 'online',
                  },
                  {
                    text: '智能体',
                    icon: 'homebar/smartAuto',
                    count: 0,
                    bodyType: 'smart',
                  },
                  {
                    text: '设置',
                    icon: 'homebar/setting',
                    count: 0,
                    bodyType: 'setting',
                  },
                ]
                  .filter((i) => i.visible !== false)
                  .map((item) => (
                    <NavItem {...item} />
                  ))}
              </div>
            }
          />
        </div>
        <div className={cls.homeContent}>
          {bodyType === 'chat' ? (
            <HomeChat session={orgCtrl.home.current.session} bodyType={bodyType} />
          ) : bodyType === 'relation' ? (
            <RelationDirectory
              session={orgCtrl.home.current.session}
              bodyType={bodyType}
            />
          ) : typeof bodyType === 'string' ? (
            <SessionBody session={orgCtrl.home.current.session} bodyType={bodyType} />
          ) : (
            renderApp(bodyType)
          )}
        </div>
      </div>
    </Spin>
  );
};
export default Home;
